package com.leesche.zcsp.node.pay.wecha.data;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.StringReader;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.SortedMap;
import java.util.TreeMap;

import javax.servlet.ServletInputStream;

import org.apache.log4j.Logger;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.JDOMException;
import org.jdom.input.SAXBuilder;
import org.xml.sax.InputSource;

import com.leesche.zcsp.node.pay.wecha.service.encha.impl.PayServiceImpl;
import com.leesche.zcsp.node.utils.PayConfig;
import com.leesche.zcsp.node.utils.RequestHandler;

public class XmlParam {
	private static final Logger logger = Logger.getLogger(XmlParam.class);
	private TreeMap<String, String> map = new TreeMap<String, String>();
	private RequestHandler reqHandler = null;
	private Document doc = null;
	
	public void putParam(String key, String val) {
		map.put(key, val);
	}

	public XmlParam(RequestHandler req)
	{
		reqHandler = req;
	}
	
	public XmlParam(ServletInputStream servletStream)
	{
		BufferedReader br = null;
		br = new BufferedReader(new InputStreamReader(
				servletStream));
		String line = null;
		StringBuilder sb = new StringBuilder();
		SAXBuilder saxbBuilder = new SAXBuilder();
		try {
			while ((line = br.readLine()) != null) {
				sb.append(line);
			}
			// 创建一个新的字符串
			StringReader read = new StringReader(sb.toString());
			// 创建新的输入源SAX 解析器将使用 InputSource 对象来确定如何读取 XML 输入
			InputSource source = new InputSource(read);
			doc = saxbBuilder.build(source);
		} catch (IOException e) {
			logger.error(e.getMessage(),e);
		}catch (JDOMException e) {
			// TODO Auto-generated catch block
			logger.error(e.getMessage(),e);
		}
		logger.info("xml param:"+sb.toString());

	}
	
	public String getParam(String key)
	{
		if (doc != null)
		{
			Element root = doc.getRootElement();
			return root.getChildText(key);
		}
		else
		{
			return null;
		}
	}
	
	public String toString() {
		String sign = reqHandler.createSign(map);
		if (sign == null) {
			return null;
		}
		putParam("sign", sign);

		StringBuffer sb = new StringBuffer();
		sb.append("<xml>");
		Set es = map.entrySet();
		Iterator it = es.iterator();
		while (it.hasNext()) {
			Map.Entry entry = (Map.Entry) it.next();
			String k = (String) entry.getKey();
			String v = (String) entry.getValue();
			{
				sb.append("<" + k + ">" +  v + "</" + k
						+ ">");
			}
		}
		sb.append("</xml>");

		return sb.toString();
	}
}
